package data

import (
	"kratosapp/internal/conf"

	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-redis/redis"
	"github.com/google/wire"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

// ProviderSet is data providers.
var ProviderSet = wire.NewSet(NewData, NewGreeterRepo)

// Data .
type Data struct {
	DBEngin *gorm.DB
	Redis   *redis.Client
}

// NewData .
func NewData(c *conf.Data, logger log.Logger) (*Data, func(), error) {
	cleanup := func() {
		log.NewHelper(logger).Info("closing the data resources")
	}
	engin, err := initDb(c, logger)
	if err != nil {
		//log.NewHelper(logger).Error(err.Error())
		panic(err.Error())
	}
	redisdb := initRedis(c, logger)
	return &Data{
		DBEngin: engin,
		Redis:   redisdb,
	}, cleanup, err
}

// 初始化redis
func initDb(c *conf.Data, logger log.Logger) (db *gorm.DB, err error) {
	db, err = gorm.Open(mysql.Open(c.Database.Source), &gorm.Config{})
	return db, err
}

// 初始化redis
func initRedis(c *conf.Data, logger log.Logger) (redisdb *redis.Client) {
	var redisOptions *redis.Options = &redis.Options{
		Addr: c.Redis.Addr,
		DB:   int(c.Redis.Index), // use default DB
	}

	if c.Redis.Password != "" {
		redisOptions.Password = c.Redis.Password
	}
	if c.Redis.ReadTimeout.IsValid() {
		redisOptions.ReadTimeout = c.Redis.ReadTimeout.AsDuration()
	}
	if c.Redis.WriteTimeout.IsValid() {
		redisOptions.WriteTimeout = c.Redis.WriteTimeout.AsDuration()

	}
	if c.Redis.MinIdleConns > 0 {
		redisOptions.MinIdleConns = int(c.Redis.MinIdleConns)
	}
	if c.Redis.Addr != "" {
		redisdb = redis.NewClient(redisOptions)
	}
	return redisdb
}
